<?php
declare (strict_types=1);

namespace app\controller\index\xisai;

// 处理希赛视频的抓取、合并、重命名（）
class Index extends \app\BaseController
{
    // 处理目录
    public $dir = 'c250008159';

    // 正则匹配数据
    public function matchData()
    {
        halt(urldecode('https://vod.cn-beijing.aliyuncs.com/?AccessKeyId=STS.NXfcsZ3bZTgaJHHDXsHJpF4F4&Action=GetPlayInfo&AuthInfo=%7B%22CI%22%3A%225Rk4pjZqrV3SvX5pm0HUoqOE6M0H9H%2FA5YnVs6d%2B4i3ZUAm6P7L75mhTcxkZpqq3IgFdgEmjcnSruUmYyBCrk17RGHmGyVvnejDYS7UYWSs%3D%22%2C%22Caller%22%3A%22%2B3M6FNG4lWqs7fLD7v9O7ItoAd6k58WFM%2BFx4trLgMU%3D%22%2C%22ExpireTime%22%3A%222025-09-02T13%3A54%3A50Z%22%2C%22MediaId%22%3A%22502bcac7e75071ef80f81777b3df0102%22%2C%22PlayDomain%22%3A%22vod1.xisaiwang.cn%22%2C%22Signature%22%3A%22WK0ZBbF4t5N1%2F1p3rf56VP0qlm4%3D%22%7D&AuthTimeout=14400&Channel=HTML5&Format=JSON&Formats=m3u8&PlayConfig=%7B%7D&PlayerVersion=2.34.0&Rand=0a22cc9b-216f-4d12-822b-8faf321b94d5&ReAuthInfo=%7B%7D&SecurityToken=CAIS1AN1q6Ft5B2yfSjIr5vTKMnu3r1746WKSG75oFgmRMVcqfHt1jz2IHhMe3ZsBewesfw2mWhS6%2F8flrIqEcQVHROaMZUovsoLr1P9JoHbvNeu0bsHhZv9jO5RtOagjqHoeOzcYI730Z7PAgm2Q0YRrJL%2BcTK9JabMU%2FmggoJmadI6RxSxaSE8av5dOgplrr0IVxzPMvr%2FHRP2um7ZHWtutA0e83145faQz9Gi6xbTi3b9zOEUqOaXJ4S%2FPfFoNYZySf6owOwUEq%2Fdy3xo7xFb1aF4i84i%2FCvc7P2QCENA%2BwmlPvu2i8NoIF1Wa7QWIYtgrfPxk%2BZ12JbNkIil5BtREdtweCnFWKGmzsy%2Bb4HPDNsicqvhMHngy82GMoKP0zkpenUGLghHCbFDQz1ScUV2EWGCdfH7pgiaPFv9G%2FS%2FvftogcYv%2FTLB5sGXIlWDebKd3BsDN4U0B0FSbEZOgjO9LvNeLFQVLgs9Wu%2FIV%2FlaaBFPtKXWmiH%2BWyNp03VLhfr6auNpbgPr1UQpNXgv8P3%2BBPwu2wNCJzx8%2B6GuN%2Fp12kZR4KeE8WgcCG6uaYX%2FtMG5S8Ao9H4pRDtUH36fAQSjx91ew0%2BVxJkXDXD8nWC5sDFkW84IeGMagAGN3yGuS0HXPzWhvWyo1Yjf0q5QhButa9j1OXR75NdZ02S0HIXkHq7Igv6CKXBEItCjWxio%2Fb0s5ij7ixdcCQQZQ5WAeMntIfZ7rnPoXiShPCsUITNaqYLrtY5gMd7kocYyOt1qlELI3qGFgxeaRJKJXst8RvzAqQNw3xe4mGyTniAA&SignatureMethod=HMAC-SHA1&SignatureNonce=9cfbfbbf-7d31-4788-90ed-88c1447fe88a&SignatureVersion=1.0&StreamType=video&Version=2017-03-21&VideoId=502bcac7e75071ef80f81777b3df0102&Signature=5t5KvbVXddbtyUMEvLtUjLt24Fc%3D'));
        $file = public_path() . 'data/xisai/' . $this->dir . '/index.html';
        $fileContent = file_get_contents($file);
        // 正则表达式模式
        // $pattern = '/<a[^>]*onclick="onVideoBFNotJumpBefore\(this\)"[^>]*data-cid="([^"]+)"[^>]*data-id="([^"]+)"[^>]*>(.*?)<\/a>/is';
        // $pattern = '/<a[^>]*[^>]*data-cid="([^"]+)"[^>]*data-id="([^"]+)"[^>]*onclick="onVideoBFNotJumpBefore\(this\)">(.*?)<\/a>/is';
        $pattern = '/<a[^>]*data-cid="([^"]+)"[^>]*data-id="([^"]+)"[^>]*onclick="onVideoBFNotJumpBefore\(this\)"[^>]*>(.*?)<\/a>/is';

        // 执行匹配
        preg_match_all($pattern, $fileContent, $matches);

        $data = [];
        for ($i = 0; $i < count($matches[0]); $i++) {
            $dataCid = $matches[1][$i];
            $dataId = $matches[2][$i];
            // 提取 span 标签内的标题
            $titlePattern = '/<span[^>]*>(.*?)<\/span>/is';
            preg_match($titlePattern, $matches[3][$i], $titleMatches);
            $title = isset($titleMatches[1]) ? trim(strip_tags($titleMatches[1])) : '';

            $data[] = [
                'data-cid' => $dataCid,
                'data-id' => $dataId,
                'title' => $title
            ];
        }

        file_put_contents(public_path() . 'data/xisai/' . $this->dir . '/data_id.json', json_encode($data, JSON_UNESCAPED_UNICODE));
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
    }

    // 通过浏览器打开链接，保存响应数据，获取m3u8格式的视频连接为json
    public function getResponseContent()
    {
        $data_id_list = json_decode(file_get_contents(public_path() . 'data/xisai/' . $this->dir . '/data_id.json'), true);
        foreach ($data_id_list as $k => $v) {
            if ($k >= 0 && $k <= 80) {
                $url = 'https://wangxiao.xisaiwang.com/wangxiao2/c' . $v['data-cid'] . '/sp' . $v['data-id'] . '.html';
                echo '<script>window.open("' . $url . '", "_blank");</script>';
            }
        }
    }

    // 获取下载链接
    public function videoInfoList()
    {
        $input_folder = public_path() . 'data/xisai/' . $this->dir . '/m3u8/';
        $iterator = \util\File::get_dirs($input_folder)['file'];

        $video_list = [];

        foreach ($iterator as $item) {
            $arr = json_decode(file_get_contents(public_path() . 'data/xisai/' . $this->dir . '/m3u8/' . $item), true);
            foreach ($arr as $value) {
                if (empty($value['PlayInfoList']['PlayInfo'][0]['PlayURL'])) continue;

                $video_list[$value['VideoBase']['VideoId']] = [
                    'VideoId' => $value['VideoBase']['VideoId'],
                    'title' => $value['VideoBase']['Title'],
                    'url' => $value['PlayInfoList']['PlayInfo'][0]['PlayURL']
                ];
            }
        }
        dump($video_list);
        file_put_contents(public_path() . 'data/xisai/' . $this->dir . '/videinfo_list.json', json_encode($video_list, JSON_UNESCAPED_UNICODE));
    }

    // 遍历m3u8.json，组装迅雷下载链接
    public function getXlDownloadUrlList()
    {
        $list = file_get_contents(public_path() . 'data/xisai/' . $this->dir . '/videinfo_list.json');
        $video_list = json_decode($list, true);
        $i = 1;
        foreach ($video_list as $k => $v) {
            echo $v['url'] . "<br/>";
        }
    }

    // 下载成功后，合并并重命名
    public function mergeAndReName()
    {
        $arr = json_decode(file_get_contents(public_path() . 'data/xisai/' . $this->dir . '/videinfo_list.json'), true);
        $new_arr = [];
        foreach ($arr as $k => $v) {
            $key = explode('-', pathinfo($v['url'])['filename'])[0];
            $new_arr[$key] = $v;
        }

        $input_folder = 'E:\迅雷下载\study_video2';
        $iterator = \util\File::get_dirs($input_folder)['dir'];

        foreach ($iterator as $dir) {
            if ($dir == '.' || $dir == '..') {
                continue;
            }

            $m3u8_path = 'E:/迅雷下载/study_video2/' . $dir . '/index.m3u8';
            $key = explode('-', $dir)[0];

            $title = $new_arr[$key]['title'];
            if ($title == 'undefined') {
                $title = $new_arr[$key]['VideoId'];
            }
            $mp4_path = 'E:/【考点强化】中级经济师经济基础知识考点强化视频教程/' . $title . '.mp4';
            if (file_exists($mp4_path)) {
                continue;
            }

            $command = 'ffmpeg -allowed_extensions ALL -i "' . $m3u8_path . '" -c copy "' . $mp4_path . '"';
            exec($command, $output, $return_var);
            if ($return_var === 0) {
                dump("成功将 $m3u8_path 合并为 $mp4_path");
            } else {
                dump("合并 $m3u8_path 失败，错误信息: " . implode("\n", $output));
            }
        }
    }

    // 重命名已出完的视频（废弃）
    public function renameVideo()
    {
        $videoInfoList = json_decode(file_get_contents(public_path() . 'data/xisai/videoIds.json'), true);
        $videoInfoList = array_column($videoInfoList, null, 'videoId');

        $input_folder = 'E:\经济师学习视频/';
        $iterator = \util\File::get_dirs($input_folder)['file'];
        foreach ($iterator as $item) {
            if (empty(explode('、', $item)[2])) continue;
            if (empty(explode('.', explode('、', $item)[2])[0])) continue;

            $key = explode('.', explode('、', $item)[2])[0];
            if (empty($videoInfoList[$key])) continue;

            // 重命名
            $new_name = implode('-', $videoInfoList[$key]) . '.mp4';
            $res = rename($input_folder . $item, $input_folder . '/' . $new_name);
            dump($res);
        }
    }
}
